import io_util
import  requests

def fund_code(code, start=None, end=None):
    '''
    字段	         类型	      描述
    code	        String	    基金代码
    name	        String	    基金名称
    type	        String	    基金类型
    netWorth	    Number	    当前基金单位净值
    expectWorth	    Number	    当前基金单位净值估算
    totalWorth	    Number	    当前基金累计净值
    expectGrowth	String	    当前基金单位净值估算日涨幅,单位为百分比
    dayGrowth	    String	    单位净值日涨幅,单位为百分比
    lastWeekGrowth	String	    单位净值周涨幅,单位为百分比
    lastMonthGrowth	String	    单位净值月涨幅,单位为百分比
    laThreeMonthsG	String	    单位净值三月涨幅,单位为百分比
    laSixMonthsG	String	    单位净值六月涨幅,单位为百分比
    lastYearGrowth	String	    单位净值年涨幅,单位为百分比
    buyMin	        Number	    起购额度
    buySourceRate	Number	    原始买入费率,单位为百分比
    buyRate	        Number	    当前买入费率,单位为百分比
    manager	        String	    基金经理
    fundScale	    String	    基金规模及日期,日期为最后一次规模变动的日期
    worthDate	    String	    净值更新日期,日期格式为yy-MM-dd HH:mm.2019-06-27 15:00代表当天下午3点
    expectWorthDate	String	    净值估算更新日期,,日期格式为yy-MM-dd HH:mm.2019-06-27 15:00代表当天下午3点
    netWorthData	String[][]	历史净值信息["2001-12-18" , 1 , 0 , ""]依次表示:日期; 单位净值; 净值涨幅; 每份分红.
    '''

    # print(code)
    # https://api.doctorxiong.club/v1/fund/detail?code=159995&startDate=2021-08-01&endDate=2021-08-08
    paras = {'code':code,'startDate':start,'endDate':end,"token":"XuIYr2F4Qh"}
    paras = {k:v for k ,v in paras.items() if v is not None}
    paras_str = "&".join(["{}={}".format(k,v) for k,v in paras.items()])
    #url = f"https://api.doctorxiong.club/v1/fund/detail?code={code}&startDate={start}&endDate={end}"
    url = f"https://api.doctorxiong.club/v1/fund/detail?"+paras_str
    # print(url)
    resp = requests.get(url)
    r = resp.json()
    return r

# fund_list = io_util.load_json('fund_list.json')
# res = {}
# for ix, d in enumerate(fund_list):
#     code = d['code']
#     try:
#         data = fund_code(code,'2021-07-01','2021-09-12')
#         res[code] = data
#     except Exception as e:
#         pass
#     if ix % 100 == 0:
#         print(ix)
#         io_util.save_json('res.json', res)
#         io_util.save_json('res100.json', res)
#     if ix % 200 == 0:
#         io_util.save_json('res200.json', res)
#io_util.save_json('res.json',res)

data = io_util.load_json('res.json')
ranks = []
last_n = 5
for code , d in data.items():
    if d['data'] is None:
        continue
    if 'netWorthData' not in d['data']:
        continue
    if  d['data']['type']!='混合型':
        continue
    data = d['data']['netWorthData']
    last_data = data[-last_n:]
    if len(last_data)!=last_n:
        continue
    start = last_data[0][1]
    end = last_data[-1][1]
    change = [float(d[2]) for d in last_data]
    pos_days = [u>0 for u in change].count(True)
    incre = (float(end)/float(start) - 1 )
    ranks.append((incre,pos_days,d))
#
ranks = sorted(ranks,key=lambda x:x[0],reverse=True)
for r in ranks[:20]:
    print(round(r[0],4),r[1],r[-1]['data']['name'],r[-1]['data']['code'])#r[-1]['data']['netWorthData'][-last_n:]